package top.shiyiri.stringclass;

import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * @author Aunean
 * @date 2022/1/1
 */
/*
String 类与其他结构之间的转换
 */
public class StringTest2 {

    /*
    String 与 byte[] 之间的转换
    String -> byte[]：调用 String 的 getBytes()
     */
    @Test
    public void test3() {
        String s1 = "abc123中国";
        byte[] bytes = s1.getBytes();
        //[97, 98, 99, 49, 50, 51, -28, -72, -83, -27, -101, -67]
        System.out.println(Arrays.toString(bytes));
        byte[] gbks = null;
        try {
            //[97, 98, 99, 49, 50, 51, -42, -48, -71, -6]
            gbks = s1.getBytes("GBK");
            System.out.println(Arrays.toString(gbks));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String s2 = new String(bytes);
        System.out.println(s2);

        String s3 = null;
        try {
            //abc123�й�   编码集和解码集不一致
            assert gbks != null;
            s3 = new String(gbks, "GBK");//abc123中国
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(s3);

        String s4 = String.valueOf(bytes);
        System.out.println(s4);//[B@5e8c92f4
    }

    /*
    String 与 char[] 之间的转换
    String -> char[] 调用 toCharArray()
    char[] -> String：调用 String 的构造器
     */
    @Test
    public void test2() {
        String s1 = "abc123";

        char[] chars = s1.toCharArray();
        System.out.println(Arrays.toString(chars));

        char[] c1 = new char[]{'h', 'e', 'l', 'l', 'o'};
        String s2 = String.valueOf(c1);
        System.out.println(s2);

        String s3 = new String(c1);
        System.out.println(s3);

        //abc123 -> a21cb3
        System.out.print(s1.charAt(0));
        for (int i = s1.length()-2; i > 0; i--) {
            System.out.print(s1.charAt(i));
        }
        System.out.print(s1.charAt(s1.length()-1));
    }

    /*
    String 与基本数据类型、包装类之间的转换
     */
    //String -> 基本数据类型、包装类：调用包装类的静态方法：parseXxx(str)
    //基本数据类型、包装类 -> String：调用 String 的静态方法：valueOf(xxx)
    @Test
    public void test1() {

        String s1 = "123";

        int i1 = Integer.parseInt(s1);
        System.out.println(i1);

        int i2 = 1234;
        String s2 = String.valueOf(i2);
        System.out.println(s2);
        String s4 = i2 + "";
    }
}
